package sk.vrto.service.crypto;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import sun.misc.*;

/**
 * Implementation of StringEncrypter that uses AES algorithm.
 */
public class AESStringEncrypter implements StringEncrypter {

    private static final String ALGORITHM = "AES";
    private static final byte[] KEY_VALUE =
            { 'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y' };

    @Override
    public String encrypt(String plain) {
        try {
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.ENCRYPT_MODE, key);
            byte[] encValue = c.doFinal(plain.getBytes());
            return new BASE64Encoder().encode(encValue);
        } catch (Exception e) {
            throw new CryptoException(e);
        }
    }

    @Override
    public String decrypt(String encrypted) {
        try {
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.DECRYPT_MODE, key);
            byte[] decordedValue = new BASE64Decoder().decodeBuffer(encrypted);
            byte[] decValue = c.doFinal(decordedValue);
            return new String(decValue);
        } catch (Exception e) {
            throw new CryptoException(e);
        }
    }

    private Key generateKey() throws Exception {
        return new SecretKeySpec(KEY_VALUE, ALGORITHM);
    }

}
